package com.hundsun.yr.universal.p2p.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.HsNumberUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.utils.SpannableStringBuilderUtils;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.NoScrollListView;
import com.hundsun.yr.universal.p2p.bean.DiscountBeen;
import com.hundsun.yr.universal.p2p.bean.DiscountInfoBean;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.ApiConstants2;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializeTargetPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import java.util.ArrayList;
import java.util.List;


/**
 * @version V1.0
 * @Title: PreferentialActivity.java
 * @Description: 优惠抵扣
 * @date 2015-12-22 下午4:11:03
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class PreferentialActivity extends BaseActivity implements InitializeView, OnItemClickListener,OnClickListener {
    /**
     * 红包listview
     **/
    private ListView lv_bonus;

    /**
     * 红包适配器
     **/
    private HolderAdapter<String> mBonusAdapter;

    /**
     * 现金listview
     **/
    private ListView lv_cash;

    /**
     * 优惠金额
     **/
    private TextView tv_discount;
    /**
     * 确认按钮
     **/
    private HSButton btn_sure;

    /**
     * 现金适配器
     **/
    private HolderAdapter<DiscountBeen.DiscountBean> mCashAdapter;

    /**
     * header视图
     **/
    private View header = null;

    /**
     * 选中Id
     **/
    private String selectId = "";

    /**
     * 红包列表
     **/
    private List<String> data_bonus = new ArrayList<String>();

    /**
     * 现金列表
     **/
    private List<DiscountBeen.DiscountBean> data_cash = new ArrayList<DiscountBeen.DiscountBean>();

    /**
     * 选中金额
     **/
    private String money = "0";

    /**
     * 商品号
     **/
    private String goodsNo;

    /**
     *
     */
    private LayoutInflater mInflater = null;

    /**
     * 网络请求红包
     */
    private RequestPresenter mPresenter = null;

    /**
     * 自定义红包优惠券
     */
    private DiscountBeen discountBean;

    /**
     * acitivity返回码
     */
    private int PREFERENTIAL = 1;

    /**
     * 加息券的listview
     */
    private NoScrollListView lv_increase_interest;
    private HolderAdapter<DiscountBeen.DiscountBean> mIncreastAdapter;
    private String min_money;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub
        goodsNo = extras.getString("GOODSNO");
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_preferential;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * BaseAppCompatActivity--获取绑定loading的视图
     *
     * @return
     */
    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        LinearLayout linear_root = findView(R.id.linear_root);
        return linear_root;
    }

    @SuppressLint("InflateParams")
    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        /**设置优惠金额**/
        setToolbarTitle(R.string.preferential_deduction);
        lv_bonus = findView(R.id.lv_bonus);
        lv_cash = findView(R.id.lv_cash);
        lv_increase_interest = findView(R.id.lv_increase_interest);

        /**
         * 抵扣金额
         */
        tv_discount = findView(R.id.tv_discount);

        /**
         * 确认按钮
         */
        btn_sure = findView(R.id.btn_sure);
        btn_sure.setOnClickListener(this);

        lv_bonus.setOnItemClickListener(this);
        lv_cash.setOnItemClickListener(this);
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //红包
        header = mInflater.inflate(R.layout.view_preferential_header, null);
        ViewCreatorHelper<String> creatorBonus = new ViewCreatorHelper<String>(R.layout.item_preferential_bonus, new UpdateItem<String>() {

            @Override
            public void refreshItem(View view, int position, String money1) {
                // TODO Auto-generated method stub
                /**红包金额**/
                TextView tv_money = findView(view, R.id.tv_money);
                tv_money.setText(SpannableStringBuilderUtils.sizeAndScriptSpan(getString(R.string._rmb, HsNumberUtils.moneyFormat(money1)), "", "", 14));
                // tv_money.setText(money1);
                /**选中图标**/
                ImageView iv_select = findView(view, R.id.iv_select);
                if (TextUtils.equals(money, money1) && selectId.isEmpty()) {
                    //点击的时候有刷新
                    iv_select.setVisibility(View.VISIBLE);
                } else {
                    iv_select.setVisibility(View.INVISIBLE);
                }
            }
        });
        mBonusAdapter = new HolderAdapter<String>(mContext, creatorBonus.viewCreator());
        lv_bonus.addHeaderView(header);
        lv_bonus.setAdapter(mBonusAdapter);

        //优惠卷
        View headers = mInflater.inflate(R.layout.view_preferential_header, null);
        TextView tv_style = findView(headers, R.id.tv_style);
        tv_style.setText(R.string.bonus);
        lv_cash.addHeaderView(headers);
        ViewCreatorHelper<DiscountBeen.DiscountBean> creatorCash = new ViewCreatorHelper<DiscountBeen.DiscountBean>(R.layout.item_preferential_cash, new UpdateItem<DiscountBeen.DiscountBean>() {

            @Override
            public void refreshItem(View view, int position, DiscountBeen.DiscountBean discounts) {
                // TODO Auto-generated method stub
                /**优惠卷金额**/
                TextView tv_money = findView(view, R.id.tv_money);
                //tv_money.setText(SpannableStringBuilderUtils.sizeAndScriptSpan(getString(R.string._rmb, HsNumberUtils.moneyFormat(discounts.amt)), getString(R.string.rmb), mContext.getString(R.string.percent), 13));
                tv_money.setText(discounts.amt);
                /**金额**/
                TextView tv_condition = findView(view, R.id.tv_condition);
                /**起投金额**/
                tv_condition.setText(getString(R.string._min_amnt, HsNumberUtils.moneyFormat(discounts.min_money)));
                /**有效期**/
                TextView tv_validdate = findView(view, R.id.tv_validdate);
                tv_validdate.setText(getString(R.string._end_validdate, discounts.start_date, discounts.end_date));
                /**红包来源**/
                TextView tv_title = findView(view, R.id.tv_title);
                tv_title.setText(discounts.name);

                /**红包期限**/
                TextView tv_can_invest_term = findView(view, R.id.tv_can_invest_term);
                if (discounts.min_term==null||discounts.min_term.equals("")){
                    tv_can_invest_term.setText(getString(R.string.invest_term_condition,discounts.max_term));
                }else {
                    tv_can_invest_term.setText(getString(R.string.invest_term_condition,discounts.max_term));
                }

                if (discounts.max_term!= null && !discounts.max_term.isEmpty() && MathUtils.compare(discounts.max_term,"0") > 0){
                    tv_can_invest_term.setText(getString(R.string.invest_term_condition2,discounts.min_term,discounts.max_term));
                }

                /**选中图标**/
                ImageView iv_select = findView(view, R.id.iv_select);
                if (TextUtils.equals(selectId, discounts.serial_id)) {
                    //点击的时候有刷新
                    iv_select.setVisibility(View.VISIBLE);
                } else {
                    iv_select.setVisibility(View.INVISIBLE);
                }

            }
        });
        mCashAdapter = new HolderAdapter<DiscountBeen.DiscountBean>(mContext, creatorCash.viewCreator());
        lv_cash.setAdapter(mCashAdapter);
        loadingData();
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    /**
     * 加载数据
     */
    private void loadingData() {
        mPresenter = new InitializeTargetPresenterImpl(mContext, this);
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.TASK_DISCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.
                TASK_DISCOUNT + "?goodsid=" + goodsNo, Constants.EVENT_REFRESH_DATA, ApiConstants2.discount(goodsNo), BaseRequestTool2.getHearder(mContext,
                TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.TASK_DISCOUNT + "?goodsid=" + goodsNo, sharedPreferences.
                        getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 选中红包/现金券
     **/
    private DiscountBeen.DiscountBean discounts = null;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        String chooseId = "";//选中id
        String chooseS = "";//选中的红包
        min_money = "";

        switch (parent.getId()) {
            case R.id.lv_bonus:
                if (position <= 0 || position > data_bonus.size()) {
                    return;
                }
                chooseS = data_bonus.get(position - 1);
                if (TextUtils.equals(money, chooseS)) {
                    money = "0";
                } else {
                    money = chooseS;
                }
                selectId = "";
                min_money = "";
                break;
            case R.id.lv_cash:
                if (position <= 0 || position > data_cash.size()) {
                    return;
                }

                discounts = data_cash.get(position - 1);
                chooseId = discounts.serial_id;
                if (TextUtils.equals(selectId, chooseId)) {
                    selectId = "";
                    money = "0";
                    min_money = "";
                } else {
                    selectId = chooseId;
                    money = discounts.amt;
                    min_money = discounts.min_money;
                }
                break;

        }

        //将价格底部导航栏价格同步
        tv_discount.setText(SpannableStringBuilderUtils.sizeAndColorSpan(getString(R.string._discount_money, money), money, 24, getResources().getColor(R.color.primary_cl_4)));
        mCashAdapter.update(data_cash);
        mBonusAdapter.update(data_bonus);
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        hideLoading();
        // TODO Auto-generated method stub
        if (TextUtils.equals(task_name, TaskConstants.TASK_DISCOUNT)) {
            if (data == null) {

                return;
            }
            refreshUI((DiscountBeen) data);
        }
    }

    /**
     * 刷新界面,优惠卷+红包
     */
    public void refreshUI(DiscountBeen data) {
        discountBean = data;
        if (discountBean.redEnvelop != null && !discountBean.redEnvelop.equals("0.00")) {
            String redEnvelop = discountBean.redEnvelop;
            data_bonus.add(redEnvelop);
        }

        List<DiscountBeen.DiscountBean> discounts = discountBean.discount;
        data_cash.addAll(discounts);

        if (data_bonus.size() == 0 && data_cash.size() == 0) {
            lv_bonus.setVisibility(View.GONE);
            lv_cash.setVisibility(View.GONE);
            showEmpty(0, mContext.getString(R.string.empty_msg), new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //如果加载画出来的数据为空，点击再试试
                }
            });
            return;
        }

        if (data_bonus.size() == 0) {
            lv_bonus.setVisibility(View.GONE);
        } else if (data_cash.size() == 0) {
            lv_cash.setVisibility(View.GONE);
        }
        mBonusAdapter.update(data_bonus);
        mCashAdapter.update(data_cash);
    }


    @Override
    public <T> void initializeError(String task_name, T data) {
        showToast(data.toString());
        hideLoading();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_sure:
                DiscountInfoBean discountInfoBean = new DiscountInfoBean(selectId, money,min_money);
                Intent intent = getIntent().putExtra("discountinfobean",discountInfoBean);
                setResult(PREFERENTIAL,intent);
                finish();
                break;
        }
    }
}
